﻿using System;
using System.ComponentModel;
using System.Windows.Forms;
using MetroFramework.Forms;
using DataTurnClient.Server;
using Splat;
using DataTurnClient.Interface;
using ReactiveUI;
using System.Reactive.Disposables;
using DataTurnClient.ViewModel;
using System.Reactive.Linq;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Drawing;
using DataTurnClient.Control;
using AntdUI;
using DataTurnClient.Controls;
using DynamicData;

namespace DataTurnClient
{
    public partial class MainTurn : MetroForm, IViewFor<MainTurnViewModel>
    {
        object IViewFor.ViewModel
        {
            get => ViewModel;
            set => ViewModel = (MainTurnViewModel)value;
        }

        public MainTurnViewModel ViewModel { get; set; }

        public MainTurn()
        {
            InitializeComponent();
            Globals.DbType = (SqlSugar.DbType)Convert.ToInt32(ConfigurationManager.AppSettings["DbType"]);
            Globals.DbConnect = ConfigurationManager.AppSettings["DbConnect"];
            this.FormClosing += Form1_FormClosing;
            this.SizeChanged += Form1_SizeChanged;
            this.Load += MainTurn_Load;
            InitBindings();
            this.KeyPreview = true;
            System.Timers.Timer t1 = new System.Timers.Timer(1000);
            t1.Elapsed += new System.Timers.ElapsedEventHandler(AllRunTime);
            t1.AutoReset = true;
            t1.Enabled = true;
        }

        //////////////////////////////////////////////
        ///写在之前
        ///时间字符串规则
        ///0:00     用:分割，前面的代表时间类型，后面代表具体的value
        ///层级，列表0代表时，列表1代表分，列表2代表秒，列表3代表如果是之间类型，所要执行的时间
        ///时间类型代码，0-未启用，1-固定类型，2-循环类型，3-之间类型
        ///特殊说明。3-之间类型
        ///例：0:00,3:87,0:00,2:20
        ///此例为，在时间是早上8点到晚上7点之间，每20分钟循环执行
        ///例：1:01

        /// <summary>
        /// 同步任务定时器
        /// </summary>
        public System.Timers.Timer timer { get; set; } = new System.Timers.Timer();

        public Job CurrentJobRows { get => metroGrid1.CurrentRow == null ? new Job() : ViewModel.JobList[metroGrid1.CurrentRow.Index]; }

        public Log CurrentLogRows { get => metroGrid2.CurrentRow == null ? new Log() : ViewModel.LogList[metroGrid2.CurrentRow.Index]; }

        /// <summary>
        /// 绑定构造
        /// </summary>
        private void InitBindings()
        {
            Locator.CurrentMutable.RegisterLazySingleton<IDBHelperService>(() => new DBHelperService());
            Locator.CurrentMutable.RegisterLazySingleton<IAntdMessage>(() => new AntdMessage());
            Locator.CurrentMutable.RegisterLazySingleton<ITool>(() => new Tool());
            Locator.CurrentMutable.RegisterLazySingleton(() => new TimeService());
            Locator.CurrentMutable.RegisterLazySingleton(() => new LogService());
            Locator.CurrentMutable.RegisterLazySingleton(() => new MainTurn());
            ViewModel = new MainTurnViewModel(RxApp.MainThreadScheduler);
            this.WhenActivated(d =>
            {

                this.BindCommand(ViewModel,
                      x => x.ClearLogGridCommand,
                      x => x.ToolStripMenuItem9)
                 .DisposeWith(d);

                metroGrid1.Events().DoubleClick.Do(x =>
                {
                    IndexAction(0,null);
                }).Subscribe().DisposeWith(d);

                metroGrid1.Events().MouseClick.Do(x =>
                {
                    if (x.Button == MouseButtons.Right)
                    {
                        var ant = Locator.Current.GetService<IAntdMessage>();
                        var config = ant.ConTextMenuConfig(metroGrid1, it =>
                        {
                            int i = Globals.ContextMenuItems.FindIndex(p => p.Text == it.Text);
                            IndexAction(i,it);
                        });
                        AntdUI.ContextMenuStrip.open(config);
                    }
                }).Subscribe().DisposeWith(d);


                metroGrid2.Events().DoubleClick.Do(x =>
                {
                    ViewModel.ShowLogMessageCommand.Execute(metroGrid2.CurrentRow == null ? 0 : metroGrid2.CurrentRow.Index).Subscribe(Result => {
                        if (Result != "") { MessageBox.Show(Result); }
                    });
                }).Subscribe().DisposeWith(d);

                this.metroLink4.Events().Click.Do(x =>
                {
                    RouteView job = new RouteView();
                    OpenDrowing(job);
                }).Subscribe().DisposeWith(d);

                this.metroLink5.Events().Click.Do(x =>
                {
                    SetView job = new SetView();
                    OpenDrowing(job);
                }).Subscribe().DisposeWith(d);

                this.metroLink6.Events().Click.Do(x =>
                {
                    TimerView job = new TimerView();
                    OpenDrowing(job);
                }).Subscribe().DisposeWith(d);

                // 任务数据源绑定
                this.OneWayBind(ViewModel,
                    vm => vm.JobList,
                    v => v.metroGrid1.DataSource)
                    .DisposeWith(d);

                // 日志数据源绑定
                this.OneWayBind(ViewModel,
                    vm => vm.LogList,
                    v => v.metroGrid2.DataSource)
                    .DisposeWith(d);

                // 定时器勾选绑定
                this.Bind(ViewModel,
                    vm => vm.IsTimer,
                    v => v.metroCheckBox5.Checked)
                    .DisposeWith(d);
            });
        }

        /*------系统方法------*/

        /*------任务------*/
        /// <summary>
        /// 定时器专用执行方法
        /// </summary>
        /// <param name="sender"></param>
        private void AllRunTime(object sender, EventArgs e)
        {
            ViewModel.IsRunTimeCommand.Execute().Subscribe();
        }
        /*------任务------*/

        /*------系统事件------*/
        private void Form1_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            if (MessageBox.Show("是否确认退出程序？", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                // 关闭所有的线程
                this.Dispose();
                this.Close();
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void MainTurn_Load(object sender, EventArgs e)
        {
            //初始化
            ViewModel.ReloadTableCommand.Execute().Subscribe(result =>
            {
                if (!result.Success)
                {
                    MessageBox.Show(result.Message);
                }
            });
            ViewModel.SelectJobCommand.Execute().Subscribe();
            ViewModel.SelectSetCommand.Execute().Subscribe();
            CheckForIllegalCrossThreadCalls = false;
        }

        private void Form1_SizeChanged(object sender, System.EventArgs e)
        {
            //判断是否选择的是最小化按钮
            if (WindowState == FormWindowState.Minimized)
            {
                //隐藏任务栏区图标
                this.ShowInTaskbar = false;
                //图标显示在托盘区
                notifyIcon1.Visible = true;
                this.Visible = false;
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, System.EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                //还原窗体显示    
                WindowState = FormWindowState.Normal;
                //激活窗体并给予它焦点
                this.Activate();
                //任务栏区显示图标
                this.ShowInTaskbar = true;
                //托盘区图标隐藏
                notifyIcon1.Visible = false;
                this.Visible = true;
            }
        }
        /*------系统事件------*/

        /*------右键方法------*/

        private void ToolStripMenuItem10_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否确认退出程序？", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                // 关闭所有的线程
                this.Dispose();
                this.Close();
            }
        }

        private void ToolStripMenuItem11_Click(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                //还原窗体显示    
                WindowState = FormWindowState.Normal;
                //激活窗体并给予它焦点
                this.Activate();
                //任务栏区显示图标
                this.ShowInTaskbar = true;
                //托盘区图标隐藏
                notifyIcon1.Visible = false;
                this.Visible = true;
            }
        }

        /// <summary>
        /// 抽屉方法，根据索引打开业务
        /// </summary>
        /// <param name="i"></param>
        /// <param name="it"></param>
        private void IndexAction(int i,ContextMenuStripItem it)
        {
            var message = Locator.Current.GetService<IAntdMessage>();
            switch (i)
            {
                case 0:
                    JobView selectJob = new JobView(Enum.DType.ControlType.Select);
                    selectJob.ViewModel.Job = CurrentJobRows;
                    var selectConfig = message.DrawerConfig(this, selectJob);
                    selectConfig.OnClose = () =>
                    {
                        ViewModel.SelectJobCommand.Execute().Subscribe();
                    };
                    AntdUI.Drawer.open(selectConfig);
                    break;
                case 1:
                    JobView addJob = new JobView(Enum.DType.ControlType.Add);
                    addJob.ViewModel.Job = new Job();
                    var addConfig = message.DrawerConfig(this, addJob);
                    addConfig.OnClose = () =>
                    {
                        ViewModel.SelectJobCommand.Execute().Subscribe();
                    };
                    AntdUI.Drawer.open(addConfig);
                    break;
                case 2:
                    JobView editJob = new JobView(Enum.DType.ControlType.Edit);
                    editJob.ViewModel.Job = CurrentJobRows;
                    var editConfig = message.DrawerConfig(this, editJob);
                    editConfig.OnClose = () =>
                    {
                        ViewModel.SelectJobCommand.Execute().Subscribe();
                    };
                    AntdUI.Drawer.open(editConfig);
                    break;
                case 3:
                    if (metroGrid1.CurrentRow != null && metroGrid1.CurrentRow.Index >= 0)
                    {
                        if (MessageBox.Show($"是否删除{ViewModel.JobList[metroGrid1.CurrentRow.Index].JobName}任务", "删除提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            ViewModel.DeleteJobCommand.Execute(CurrentJobRows).Subscribe(result =>
                            {
                                if (!result.Success)
                                {
                                    MessageBox.Show($"请求失败，{result.Message}");
                                }
                            });
                        }
                    }
                    break;
                case 4:
                    if (!string.IsNullOrEmpty(CurrentJobRows.JobCode))
                    {
                        ViewModel.ChangeJobStatusCommand.Execute(CurrentJobRows.JobCode).Subscribe();
                    }
                    break;
                case 5:
                    if (!string.IsNullOrEmpty(CurrentJobRows.JobCode))
                    {
                        ViewModel.RunJobCommand.Execute(CurrentJobRows.JobCode).Subscribe();
                    }
                    break;
                case 6:
                    ViewModel.SelectJobCommand.Execute().Subscribe();
                    break;
                case 7:
                    ViewModel.RunAllJobCommand.Execute().Subscribe();
                    break;
                default:
                    Console.WriteLine($"点击：{it.Text}");
                    break;
            }
        }

        /// <summary>
        /// 根据控件打开抽屉
        /// </summary>
        /// <param name="Control"></param>
        private void OpenDrowing(System.Windows.Forms.Control Control)
        {
            var message = Locator.Current.GetService<IAntdMessage>();

            var config = message.DrawerConfig(this, Control);
            config.OnClose = () =>
            {
                ViewModel.SelectJobCommand.Execute().Subscribe();
                ViewModel.SelectSetCommand.Execute().Subscribe();
            };
            AntdUI.Drawer.open(config);
        }

    }
}
